package br.com.projeto.web.vraptor.componentes;

import java.util.ResourceBundle;

import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.ioc.RequestScoped;
import br.com.caelum.vraptor.resource.ResourceMethod;

@Component
@RequestScoped
public class ContentResourceBundle {

	private static String EQUIPE = "{equipe}";
	private static String PROJETO = "{projeto}";
	private static String USUARIO = "{usuario}";

	private static ResourceBundle BUNDLE;

	private SessionUser session;
	private Result result;

	public ContentResourceBundle(SessionUser session, Result result) {
		this.session = session;
		this.result = result;

		if (BUNDLE == null)
			BUNDLE = ResourceBundle.getBundle("content");
	}

	public void addContentFor(ResourceMethod action) {
		String method = simpleNameFor(action);
		
		String title = String.format("%s.%s", method, "title");
		String help = String.format("%s.%s", method, "help");
		String header = String.format("%s.%s", method, "header");

		if (BUNDLE.containsKey(title))
			result.include("title",
					addSessionVariables(BUNDLE.getString(title)));

		if (BUNDLE.containsKey(help))
			result.include("help", addSessionVariables(BUNDLE.getString(help)));

		if (BUNDLE.containsKey(header))
			result.include("pageHeader", addSessionVariables(BUNDLE
					.getString(header)));

	}

	private String simpleNameFor(ResourceMethod action) {
		String resource = action.getResource().getType().getSimpleName()
				.replaceAll("Controller", "").toLowerCase();
		String method = action.getMethod().getName().toLowerCase();
		
		return String.format("%s.%s", resource, method);
	}

	private String addSessionVariables(String value) {

		if (value.contains(EQUIPE))
			value = value.replace(EQUIPE, session.getEquipe().getNome());

		if (value.contains(USUARIO))
			value = value.replace(USUARIO, session.getUsuario()
					.getPrimeiroNome());

		if (value.contains(PROJETO))
			value = value.replace(PROJETO, session.getProjeto().getTitulo());

		return value;
	}
}
